package com.work.demo.test;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;

/**
 * 接口结果
 *
 * @author admin
 */
@Data
public class ResultDTO<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    private static final Integer SUCCESS_CODE = 0;
    private String msg;
    private Integer code;
    private T data;

    public static <T> ResultDTO<T> success(T data) {
        ResultDTO<T> result = new ResultDTO<>();
        result.data = data;
        result.code = 0;
        result.msg = "成功";
        return result;
    }

    public static <T> ResultDTO<T> success(T data, String mesage) {
        ResultDTO<T> result = new ResultDTO<>();
        result.data = data;
        result.code = 0;
        result.msg = mesage;
        return result;
    }

    public static <T> ResultDTO<T> success() {
        return success(null);
    }

    public static <T> ResultDTO<T> error(int code, String msg) {
        ResultDTO<T> result = new ResultDTO<>();
        result.code = code;
        result.msg = doReplaceSensitives(msg);
        return result;
    }

    public static <T> ResultDTO<T> error(BaseError err) {
        return error(err.getCode(), err.getMsg());
    }

    public static <T> ResultDTO<T> error(BaseError err, String msg) {
        return error(err.getCode(), msg);
    }


    @JsonIgnore
    public boolean isSuccess() {
        return SUCCESS_CODE.equals(code);
    }

    public static <T> boolean isSuccess(ResultDTO<T> result) {
        return result != null && result.isSuccess();
    }

    /**
     * 敏感词替换  (avatar + cn.fudata. + cn.fudata + fudata 替换为空,且忽略大小写)
     *
     * @param strs
     * @return
     */
    private static String doReplaceSensitives(String strs) {
        if (StringUtils.isBlank(strs)) {
            return strs;
        }
        String regex = "(?i)(avatar|cn.fudata.|cn.fudata|fudata)";
        return strs.replaceAll(regex, "");
    }
}